define([], function () {
    require.config({
    paths: {
        'nkeditor': '../addons/nkeditor/js/customplugin',
        'nkeditor-core': '../addons/nkeditor/nkeditor.min',
        'nkeditor-lang': '../addons/nkeditor/lang/zh-CN',
    },
    shim: {
        'nkeditor': {
            deps: [
                'nkeditor-core',
                'nkeditor-lang'
            ]
        },
        'nkeditor-core': {
            deps: [
                'css!../addons/nkeditor/themes/black/editor.min.css',
                'css!../addons/nkeditor/css/common.css'
            ],
            exports: 'window.KindEditor'
        },
        'nkeditor-lang': {
            deps: [
                'nkeditor-core'
            ]
        }
    }
});
require(['form'], function (Form) {
    var _bindevent = Form.events.bindevent;
    Form.events.bindevent = function (form) {
        _bindevent.apply(this, [form]);
        if ($(".editor", form).size() > 0) {
            require(['nkeditor', 'upload'], function (Nkeditor, Upload) {
                var getImageFromClipboard, getImageFromDrop, getFileFromBase64;
                getImageFromClipboard = function (data) {
                    var i, item;
                    i = 0;
                    while (i < data.clipboardData.items.length) {
                        item = data.clipboardData.items[i];
                        if (item.type.indexOf("image") !== -1) {
                            return item.getAsFile() || false;
                        }
                        i++;
                    }
                    return false;
                };
                getImageFromDrop = function (data) {
                    var i, item, images;
                    i = 0;
                    images = [];
                    while (i < data.dataTransfer.files.length) {
                        item = data.dataTransfer.files[i];
                        if (item.type.indexOf("image") !== -1) {
                            images.push(item);
                        }
                        i++;
                    }
                    return images;
                };
                getFileFromBase64 = function (data, url) {
                    var arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    var filename, suffix;
                    if (typeof url != 'undefined') {
                        var urlArr = url.split('.');
                        filename = url.substr(url.lastIndexOf('/') + 1);
                        suffix = urlArr.pop();
                    } else {
                        filename = Math.random().toString(36).substring(5, 15);
                    }
                    console.log(filename);
                    if (!suffix) {
                        suffix = data.substring("data:image/".length, data.indexOf(";base64"));
                    }

                    var exp = new RegExp("\\." + suffix + "$", "i");
                    filename = exp.test(filename) ? filename : filename + "." + suffix;
                    var file = new File([u8arr], filename, {type: mime});
                    return file;
                };

                var getImageFromUrl = function (url, callback, outputFormat) {
                    var canvas = document.createElement('CANVAS'),
                        ctx = canvas.getContext('2d'),
                        img = new Image;
                    img.crossOrigin = 'Anonymous';
                    img.onload = function () {
                        var urlArr = url.split('.');
                        var suffix = urlArr.pop();
                        suffix = suffix.match(/^(jpg|png|gif|bmp|jpeg)$/i) ? suffix : 'png';

                        try {
                            canvas.height = img.height;
                            canvas.width = img.width;
                            ctx.drawImage(img, 0, 0);
                            var dataURL = canvas.toDataURL(outputFormat || 'image/' + suffix);
                            var file = getFileFromBase64(dataURL, url);
                        } catch (e) {
                            callback.call(this, null);
                        }

                        callback.call(this, file);
                        canvas = null;
                    };
                    img.onerror = function (e) {
                        callback.call(this, null);
                    };
                    img.src = url;
                };
                //上传Word图片
                Nkeditor.uploadwordimage = function (index, image) {
                    var that = this;
                    (function () {
                        var file = getFileFromBase64(image);
                        var placeholder = new RegExp("##" + index + "##", "g");
                        Upload.api.send(file, function (data) {
                            that.html(that.html().replace(placeholder, Fast.api.cdnurl(data.url)));
                        }, function (data) {
                            that.html(that.html().replace(placeholder, ""));
                        });
                    }(index, image));
                };

                Nkeditor.lang({
                    remoteimage: '下载远程图片'
                });
                //远程下载图片
                Nkeditor.plugin('remoteimage', function (K) {
                    var editor = this, name = 'remoteimage';
                    editor.plugin.remoteimage = {
                        download: function (e) {
                            var that = this;
                            var html = that.html();
                            var staging = {}, orgined = {}, index = 0, images = 0, completed = 0, failured = 0;
                            var checkrestore = function () {
                                if (completed + failured >= images) {
                                    $.each(staging, function (i, j) {
                                        that.html(that.html().replace("<code>" + i + "</code>", j));
                                    });
                                }
                            };
                            html.replace(/<code>([\s\S]*?)<\/code>/g, function (code) {
                                    staging[index] = code;
                                    return "<code>" + index + "</code>";
                                }
                            );
                            html = html.replace(/<img([\s\S]*?)\ssrc\s*=\s*('|")((http(s?):)([\s\S]*?))('|")([\s\S]*?)[\/]?>/g, function () {
                                images++;
                                var url = arguments[3];
                                var placeholder = '<img src="' + Fast.api.cdnurl("/assets/addons/nkeditor/img/downloading.png") + '" data-index="' + index + '" />';
                                //如果是云存储的链接,则忽略
                                if (Config.upload.cdnurl && url.indexOf(Config.upload.cdnurl) > -1) {
                                    completed++;
                                    return arguments[0];
                                } else {
                                    orgined[index] = arguments[0];
                                }
                                //下载远程图片
                                (function (index, url, placeholder) {
                                    getImageFromUrl(url, function (file) {
                                        if (!file) {
                                            failured++;
                                            that.html(that.html().replace(placeholder, orgined[index]));
                                            checkrestore();
                                        } else {
                                            Upload.api.send(file, function (data) {
                                                completed++;
                                                that.html(that.html().replace(placeholder, '<img src="' + Fast.api.cdnurl(data.url) + '" />'));
                                                checkrestore();
                                            }, function (data) {
                                                failured++;
                                                that.html(that.html().replace(placeholder, orgined[index]));
                                                checkrestore();
                                            });
                                        }
                                    });
                                })(index, url, placeholder);
                                index++;
                                return placeholder;
                            });
                            if (index > 0) {
                                that.html(html);
                            } else {
                                Toastr.info("没有需要下载的远程图片");
                            }
                        }
                    };
                    // 点击图标时执行
                    editor.clickToolbar(name, editor.plugin.remoteimage.download);
                });

                $(".editor", form).each(function () {
                    var that = this;
                    Nkeditor.create(that, {
                        width: '100%',
                        filterMode: false,
                        wellFormatMode: false,
                        allowMediaUpload: true, //是否允许媒体上传
                        allowFileManager: true,
                        allowImageUpload: true,
                        wordImageServer: typeof Config.nkeditor != 'undefined' && Config.nkeditor.wordimageserver ? "127.0.0.1:10101" : "", //word图片替换服务器的IP和端口
                        urlType: Config.upload.cdnurl ? 'domain' : '',//给图片加前缀
                        cssPath: Fast.api.cdnurl('/assets/addons/nkeditor/plugins/code/prism.css'),
                        cssData: "body {font-size: 13px}",
                        fillDescAfterUploadImage: false, //是否在上传后继续添加描述信息
                        themeType: typeof Config.nkeditor != 'undefined' ? Config.nkeditor.theme : 'black', //编辑器皮肤,这个值从后台获取
                        fileManagerJson: Fast.api.fixurl("/addons/nkeditor/index/attachment/module/" + Config.modulename),
                        items: [
                            'source', 'undo', 'redo', 'preview', 'print', 'template', 'code', 'quote', 'cut', 'copy', 'paste',
                            'plainpaste', 'wordpaste', 'justifyleft', 'justifycenter', 'justifyright',
                            'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                            'superscript', 'clearhtml', 'quickformat', 'selectall',
                            'formatblock', 'fontname', 'fontsize', 'forecolor', 'hilitecolor', 'bold',
                            'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', 'image', 'multiimage', 'graft',
                            'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
                            'anchor', 'link', 'unlink', 'remoteimage', 'about', 'fullscreen'
                        ],
                        afterCreate: function () {
                            var self = this;
                            //Ctrl+回车提交
                            Nkeditor.ctrl(document, 13, function () {
                                self.sync();
                                $(that).closest("form").submit();
                            });
                            Nkeditor.ctrl(self.edit.doc, 13, function () {
                                self.sync();
                                $(that).closest("form").submit();
                            });
                            //粘贴上传
                            $("body", self.edit.doc).bind('paste', function (event) {
                                var image, pasteEvent;
                                pasteEvent = event.originalEvent;
                                if (pasteEvent.clipboardData && pasteEvent.clipboardData.items) {
                                    image = getImageFromClipboard(pasteEvent);
                                    if (image) {
                                        event.preventDefault();
                                        Upload.api.send(image, function (data) {
                                            self.exec("insertimage", Fast.api.cdnurl(data.url));
                                        });
                                    }
                                }
                            });
                            //挺拽上传
                            $("body", self.edit.doc).bind('drop', function (event) {
                                var image, pasteEvent;
                                pasteEvent = event.originalEvent;
                                if (pasteEvent.dataTransfer && pasteEvent.dataTransfer.files) {
                                    images = getImageFromDrop(pasteEvent);
                                    if (images.length > 0) {
                                        event.preventDefault();
                                        $.each(images, function (i, image) {
                                            Upload.api.send(image, function (data) {
                                                self.exec("insertimage", Fast.api.cdnurl(data.url));
                                            });
                                        });
                                    }
                                }
                            });
                        },
                        //FastAdmin自定义处理
                        beforeUpload: function (callback, file) {
                            var file = file ? file : $("input.ke-upload-file", this.form).prop('files')[0];
                            Upload.api.send(file, function (data) {
                                var data = {code: '000', data: {url: Fast.api.cdnurl(data.url)}, title: '', width: '', height: '', border: '', align: ''};
                                callback(data);
                            });

                        },
                        //错误处理 handler
                        errorMsgHandler: function (message, type) {
                            try {
                                console.log(message, type);
                            } catch (Error) {
                                alert(message);
                            }
                        }
                    });
                });
            });
        }
    }
});

//如果开启了OSS客户端上传模式
if (typeof Config.upload.storage !== 'undefined' && Config.upload.storage === 'oss') {
    require(['upload', '../addons/oss/js/spark'], function (Upload, SparkMD5) {

    	console.log('Upload',Upload);

        var _onFileAdded = Upload.events.onFileAdded;
        var _onUploadResponse = Upload.events.onUploadResponse;
        
        window.oss_upload_conf = window.oss_upload_conf || undefined;

        var _process = function (up, file, cb) {
            var blob = file.getNative();
            var loadedBytes = file.loaded;
            var chunkSize = 2097152;
            var chunkBlob = blob.slice(loadedBytes, loadedBytes + chunkSize);
            var reader = new FileReader();
            reader.addEventListener('loadend', function (e) {
                var spark = new SparkMD5.ArrayBuffer();
                spark.append(e.target.result);
                var md5 = spark.end();
                file.md5 = md5;
                up.start();
                if( cb && cb instanceof Function )
    				return cb(up,file);
                return;
            });
            reader.readAsArrayBuffer(chunkBlob);
        };

        var random_string = function(len) 
        {
		　　len = len || 32;
		　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
		　　var maxPos = chars.length;
		　　var pwd = '';
		　　for (i = 0; i < len; i++) {
		    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
		    }
		    return pwd;
		}

		var get_suffix = function(filename) {
		    pos = filename.lastIndexOf('.')
		    suffix = ''
		    if (pos != -1) {
		        suffix = filename.substring(pos)
		    }
		    return suffix;
		}

		var builObjUrl = function(obj_name)
		{
			var cdnurl = window.oss_upload_conf.cdnurl || Config.upload.cdnurl || '';
			var dir = window.oss_upload_conf.dir || '';
			if( cdnurl != '' )
			{
				var url = /.*?\/$/.test(cdnurl) ? cdnurl+obj_name : cdnurl+"/"+obj_name ;
			}else{
				var host = window.oss_upload_conf.host;
				var url = /.*?\/$/.test(host) ? host+obj_name : host+"/"+obj_name ;
			}

			return url ;
		}

		var createFileName = function(file,len)
		{
			if( window.oss_upload_conf.savekey!='' )
			{
				var baseName = window.oss_upload_conf.dir+""+ window.oss_upload_conf.savekey;
				var date = new Date();
				var suffix = get_suffix(file.name);
				var filename = baseName.replace(/\s/g,'');
				var filename = baseName.replace(/\/\//g,'/');
				    filename = filename.replace(/\{year\}/g,date.getFullYear());
					filename = filename.replace(/\{mon\}/g,date.getMonth()+1);
					filename = filename.replace(/\{day\}/g,date.getDay());
					filename = filename.replace(/\{filemd5\}/g,file.md5);
					filename = filename.replace(/\{oname\}/g,file.name.replace(suffix, ''));
					filename = filename.replace(/\{\.suffix\}/g,suffix);
					filename = filename.replace(/\{suffix\}/g,suffix.replace(".",""));
				return filename;
			}
			return window.oss_upload_conf.dir +"" + random_string(len) + get_suffix(file.name);
		}

        var getToken = function( up, file, cb, force  )
        {
        	if( !force || force !== true )
        	{
        		if( window.oss_upload_conf )
        		{
        			var now = parseInt( (new Date()).getTime()/1000 );
        			if( window.oss_upload_conf.expire > now + 3 )
        			{
        				if( cb && cb instanceof Function )
        					return cb(window.oss_upload_conf);

        				return false;
        			}
        		}
        	}

        	Fast.api.ajax({
                url: "/addons/oss/index/token",
                data: {
                	name: file.name, 
                	type: file.type, 
                	size: file.size
                },
            }, function (data) 
            {
                if(data && data.token && 'object' == typeof data.token )
                {
                	console.log("token",data.token);

                	window.oss_upload_conf = data.token;

                	if( cb && cb instanceof Function )
        				return cb(window.oss_upload_conf);
                }

                console.log("token请求完毕",data);
                
                return false;
            });
        }


        Upload.events.onFileAdded = function (up, files) {
        	console.log('onFileAdded',undefined == window.oss_upload_conf,window.oss_upload_conf);
        	if( undefined == window.oss_upload_conf )
        	{
        		up.stop();
        		return getToken(up,files[0],function(){
        			Upload.events.onFileAdded(up, files);
        		})
        	}
            return _onFileAdded.call(this, up, files);           
        };

        Upload.events.onBeforeUpload = function (up, file) 
        {
        	if ( typeof file.md5 === 'undefined') 
        	{ 
        		up.stop();
        		console.log('暂停上传md5，没有');
                return _process(up, file,function(up,file){        			
        			Upload.events.onBeforeUpload(up,file);
        		});
            }

            console.log('md5有了');

            if( undefined == window.oss_upload_conf )
        	{
        		up.stop();
        		console.log('暂停上传，conf没有');
        		return getToken(up,file,function(up,file){        			
        			Upload.events.onBeforeUpload(up,file);
        		})
        	}
        	
        	console.log('conf有了');

        	file.obj_name = createFileName(file,16);   

        	up.setOption({
		        'url': window.oss_upload_conf.host,
		        'multipart_params': {
			        'key' : file.obj_name,
			        'policy': window.oss_upload_conf.policy,
			        'OSSAccessKeyId': window.oss_upload_conf.accessid, 
			        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
			        'callback' : "",
			        'signature': window.oss_upload_conf.signature,
			    }
		    });

			window.upLoadUp = up;
			console.log('up，开始上传',up);
			up.start();		    
        };
        Upload.events.onUploadResponse = function (response, info, up, file) {
        	console.log("上传完毕1",info,file);
        	var ret = {};
            if (info&&info.status&&info.status === 200) {
                ret.code = 1;
                ret.data = {
                    url: builObjUrl(file.obj_name)
                };
            } else {
                ret.code = 0;
                ret.msg = info.response;
            }

            console.log("上传完毕2",ret,file);
            return _onUploadResponse.call(this, JSON.stringify(ret));       
        };
    });
}
});